<template>
    <ayjDialog :title="title" width="30%" ref="ayjDialogRef" :slotFooter="true" @closeFun="handleClose">
        <div class="customer_points_top bg_gray flex_between">
            <div class="flex_row">
                <img class="imgWHAvatar" :src="getYyInfoData.avatar" alt="">
                <div class="ml10">
                    <div class="font_size14 bold">{{ getYyInfoData.name || '--' }}</div>
                    <div class="font_size12">{{ getYyInfoData.company || '--' }}</div>
                </div>
            </div>
            <div class="flex_center_column">
                <div class="">可用积分</div>
                <div class="font_green font_size18">{{ p_fract || '--' }}</div>
            </div>
        </div>
        <div class="mt20">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="兑换店铺" prop="idyun">
                    <el-select style="width: 300px;" v-model="form.idyun" placeholder="请选择" @change="selectHandleChange">
                        <el-option v-for="item in yd_ls" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="兑换积分" prop="p">
                    <el-input type="number" :min="0" style="width: 300px;" v-model="form.p"
                        placeholder="请输入兑换的积分"></el-input>
                </el-form-item>
                <el-form-item label="兑换类型" prop="type">
                    <el-select style="width: 300px;" v-model="form.type" placeholder="请选择"
                        :popper-append-to-body="false">
                        <el-option v-for="item in type_ls" :key="item.value"
                            :label="item.title + (item.txt ? '（' + item.txt + '）' : '')" :value="item.value"
                            class="custom-option">
                            <span>{{ item.title }}</span>
                            <span class="small-text" v-if="item.txt">（{{ item.txt }}）</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="txt">
                    <el-input style="width: 300px;" v-model="form.txt" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <div slot="footer" class="flex_center">
            <el-button size="mini" @click="handleCancel">取 消</el-button>
            <el-button size="mini" type="primary" @click="handleSubmit">确 定</el-button>
        </div>
    </ayjDialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance, defineProps, defineExpose, watch, defineEmits } from '@vue/composition-api'
const { proxy } = getCurrentInstance();

import config from "@/js/conf/Config.js";
import localStore from "@/js/LocalStore.js";

const ayjDialogRef = ref(null)
const formRef = ref(null)
const p_fract = ref('')
const idyun = ref('')

const form = reactive({
    customerid: '',
    idyun: '',
    p: '',
    type: '',
    txt: '',
    ch: '', // 1增加-获取方向   2减少-兑换类型
})

const rules = reactive({
    idyun: [
        { required: true, message: '请选择兑换店铺', trigger: 'change' }
    ],
    p: [
        { required: true, message: '请输入兑换积分', trigger: 'blur' },
        { pattern: /^[1-9]\d*$/, message: '积分必须为大于0的整数', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择兑换类型', trigger: 'change' }
    ],
})

const props = defineProps({
    getYyInfoData: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['refresh'])

watch(() => props.getYyInfoData, (newVal) => {
    if (newVal?.id) {
        pFractFun();
    }
}, { deep: true })

const yd_ls = ref([])

const title = ref('')
const open = (type) => {
    if (type == 'add') {
        title.value = '添加积分'
        form.ch = '1'
    } else if (type == 'exchange') {
        title.value = '兑换积分'
        form.ch = '2'
    }
    ayjDialogRef.value.open();
    if (props.getYyInfoData.id) {
        form.customerid = props.getYyInfoData.id
        type_ls.value = []
        pFractFun();
        typeLsFun();
    }
}

const handleClose = () => {
    ayjDialogRef.value.close();
    formRef.value?.resetFields();
}

const selectHandleChange = () => {
    pFractFun();
}

const pFractFun = async () => {
    let url = config.CUSTOM_P_FRACT;
    let cp = await localStore.getCpInfo();
    let param = {
        cpid: cp.id,
        customerid: props.getYyInfoData.id,
        idyun: form.idyun,
    };
    let res = await proxy.$api({ url: url, data: param });
    if (res.status == 1) {
        p_fract.value = res.data.p_fract;
        yd_ls.value = res.data.yd_ls.filter(item => item.idyun != '0').map(item => {
            return {
                ...item,
                value: item.idyun,
                label: item.name
            }
        });
    }
}

// 获取类型
const type_ls = ref([])
const typeLsFun = async () => {
    let url = config.CUSTOM_RRACT_TYPE_LS;
    let param = {
        ch: form.ch,
    };
    let res = await proxy.$api({ url: url, data: param });
    if (res.status == 1) {
        let result = [...(res.data?.type_ls_sys || []), ...(res.data?.type_ch || [])]
        type_ls.value = result.map(item => {
            return {
                ...item,
                value: item.id,
                label: item.title + (item.txt ? '（' + item.txt + '）' : ''),
                title: item.title,
                txt: item.txt
            }
        });
    }
}

const handleCancel = () => {
    ayjDialogRef.value.close();
    formRef.value?.resetFields();
}

const handleSubmit = async () => {
    if (!formRef.value) return;
    try {
        await formRef.value.validate();
        // 表单验证通过，执行保存操作
        await savesGradeFun();
    } catch (error) {
        console.error('表单验证失败:', error);
    }
}

const savesGradeFun = async () => {
    try {
        // 这里添加保存积分的逻辑
        let param = {
            ...form
        };
        let res = await proxy.$api({ url: config.custom_fract_save, data: param });
        if (res.status == 1) {
            pFractFun();
            formRef.value?.resetFields();
            ayjDialogRef.value.close();
            emit('refresh')
            proxy.$message({
                message: '操作成功',
                type: 'success'
            });
        }   
    } catch (error) {
        proxy.$message({
            message: '操作失败',
            type: 'error'
        });
    }
}

defineExpose({
    open
})
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
    padding: 10px 0 !important;
}

.customer_points_top {
    padding: 10px 14px;
    border-radius: 6px;
}

.select_store ::v-deep .el-input__inner {
    background-color: #f5f5f5 !important;
    border: none !important;
    color: #333 !important;
    padding-left: 4px !important;
    text-align: left !important;
    border-bottom: 1px solid #e9dede !important;
    border-radius: 0 !important;
}

.imgWHAvatar {
    width: 50px;
    height: 50px;
}

.custom-option .small-text {
    font-size: 12px !important;
    color: #999;
}

</style>
